<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :lg="6" :gutter="20">
        <el-card class="box-card statistic-card">
          <div slot="header" class="clearfix">
            <span>连接设备</span>
            <el-tag v-if="stats.connectedDevices > 0" type="success" size="mini">运行中</el-tag>
            <el-tag v-else type="info" size="mini">离线</el-tag>
          </div>
          <div class="statistic-content">
            <count-to :start-val="0" :end-val="stats.connectedDevices" :duration="3000" class="statistic-number"/>
            <div class="statistic-label">设备在线</div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6" :gutter="20">
        <el-card class="box-card statistic-card">
          <div slot="header" class="clearfix">
            <span>平台客户端</span>
          </div>
          <div class="statistic-content">
            <count-to :start-val="0" :end-val="stats.connectedPlatformClients" :duration="3000" class="statistic-number"/>
            <div class="statistic-label">代理连接</div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6" :gutter="20">
        <el-card class="box-card statistic-card">
          <div slot="header" class="clearfix">
            <span>上行消息</span>
          </div>
          <div class="statistic-content">
            <count-to :start-val="0" :end-val="stats.totalMessagesUp" :duration="3000" class="statistic-number"/>
            <div class="statistic-label">
              <span class="rate">{{ stats.messageRateUp }}/分钟</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6" :gutter="20">
        <el-card class="box-card statistic-card">
          <div slot="header" class="clearfix">
            <span>下行消息</span>
          </div>
          <div class="statistic-content">
            <count-to :start-val="0" :end-val="stats.totalMessagesDown" :duration="3000" class="statistic-number"/>
            <div class="statistic-label">
              <span class="rate">{{ stats.messageRateDown }}/分钟</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 连接设备列表 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>连接设备列表</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">刷新</el-button>
          </div>
          <el-table v-loading="loading" :data="deviceList" style="width: 100%">
            <el-table-column label="设备ID" prop="clientId" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag size="small">{{ scope.row.clientId }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success" size="small">在线</el-tag>
                <el-tag v-else type="info" size="small">离线</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="消息统计" width="120">
              <template slot-scope="scope">
                <span class="message-count">↑{{ scope.row.upMessageCount }}</span>
                <span class="message-count">↓{{ scope.row.downMessageCount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最后活动" width="140">
              <template slot-scope="scope">
                <span v-if="scope.row.lastMessageTime">{{ parseTime(scope.row.lastMessageTime) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 平台客户端列表 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>平台代理客户端</span>
          </div>
          <el-table v-loading="loading" :data="platformClientList" style="width: 100%">
            <el-table-column label="客户端ID" prop="platformClientId" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag size="small" type="warning">{{ scope.row.platformClientId }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="对应设备" prop="deviceClientId" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.deviceClientId }}
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success" size="small">在线</el-tag>
                <el-tag v-else type="info" size="small">离线</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="最后活动" width="140">
              <template slot-scope="scope">
                <span v-if="scope.row.lastMessageTime">{{ parseTime(scope.row.lastMessageTime) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 实时消息流水 -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>实时消息流水</span>
            <el-button-group style="float: right;">
              <el-button :type="autoRefresh ? 'primary' : ''" size="mini" @click="toggleAutoRefresh">
                {{ autoRefresh ? '停止刷新' : '自动刷新' }}
              </el-button>
              <el-button size="mini" @click="refreshMessages">刷新</el-button>
              <el-button size="mini" @click="clearMessages">清空</el-button>
            </el-button-group>
          </div>
          <el-table v-loading="messageLoading" :data="messageList" style="width: 100%" max-height="400">
            <el-table-column label="时间" width="160">
              <template slot-scope="scope">
                {{ parseTime(scope.row.createTime, '{h}:{i}:{s}') }}
              </template>
            </el-table-column>
            <el-table-column label="设备ID" prop="clientClientId" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag size="mini">{{ scope.row.clientClientId }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="方向" width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.direction === 'up'" type="success" size="mini">↑ 上行</el-tag>
                <el-tag v-else type="warning" size="mini">↓ 下行</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="设备主题" prop="deviceTopic" show-overflow-tooltip>
              <template slot-scope="scope">
                <code>{{ scope.row.deviceTopic }}</code>
              </template>
            </el-table-column>
            <el-table-column label="平台主题" prop="platformTopic" show-overflow-tooltip>
              <template slot-scope="scope">
                <code v-if="scope.row.platformTopic">{{ scope.row.platformTopic }}</code>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 'success'" type="success" size="mini">成功</el-tag>
                <el-tag v-else type="danger" size="mini">失败</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="showMessageDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 消息详情对话框 -->
    <el-dialog title="消息详情" :visible.sync="messageDetailVisible" width="60%">
      <el-form label-width="100px">
        <el-form-item label="消息方向">
          <el-tag v-if="currentMessage.direction === 'up'" type="success">上行</el-tag>
          <el-tag v-else type="warning">下行</el-tag>
        </el-form-item>
        <el-form-item label="设备主题">
          <code>{{ currentMessage.deviceTopic }}</code>
        </el-form-item>
        <el-form-item label="平台主题">
          <code>{{ currentMessage.platformTopic || '-' }}</code>
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input
            type="textarea"
            :rows="8"
            readonly
            v-model="currentMessage.messageContent"
            placeholder="消息内容">
          </el-input>
        </el-form-item>
        <el-form-item label="错误信息" v-if="currentMessage.errorMessage">
          <el-alert
            :title="currentMessage.errorMessage"
            type="error"
            :closable="false">
          </el-alert>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="messageDetailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSystemStats, getConnectedDevices, getPlatformClients, getRecentMessages } from '@/api/iot/gatewayMonitor'
import CountTo from 'vue-count-to'

export default {
  name: 'GatewayMonitor',
  components: { CountTo },
  data() {
    return {
      // 统计信息
      stats: {
        connectedDevices: 0,
        connectedPlatformClients: 0,
        totalMessagesUp: 0,
        totalMessagesDown: 0,
        messageRateUp: 0,
        messageRateDown: 0,
        serverStartTime: null,
        currentTime: null
      },
      // 设备列表
      deviceList: [],
      // 平台客户端列表
      platformClientList: [],
      // 消息列表
      messageList: [],
      // 加载状态
      loading: false,
      messageLoading: false,
      // 自动刷新
      autoRefresh: true,
      refreshTimer: null,
      // 消息详情
      messageDetailVisible: false,
      currentMessage: {}
    }
  },
  mounted() {
    this.loadData()
    this.startAutoRefresh()
    this.initWebSocket()
  },
  beforeDestroy() {
    this.stopAutoRefresh()
    if (this.ws) {
      this.ws.close()
    }
  },
  methods: {
    // 加载数据
    loadData() {
      this.loading = true
      Promise.all([
        getSystemStats(),
        getConnectedDevices(),
        getPlatformClients(),
        getRecentMessages(20)
      ]).then(([statsRes, devicesRes, clientsRes, messagesRes]) => {
        this.stats = statsRes.data
        this.deviceList = devicesRes.data
        this.platformClientList = clientsRes.data
        this.messageList = messagesRes.data
        this.loading = false
        this.messageLoading = false
      }).catch(() => {
        this.loading = false
        this.messageLoading = false
      })
    },

    // 刷新消息
    refreshMessages() {
      this.messageLoading = true
      getRecentMessages(20).then(response => {
        this.messageList = response.data
        this.messageLoading = false
      })
    },

    // 清空消息
    clearMessages() {
      this.messageList = []
    },

    // 刷新数据
    refreshData() {
      this.loadData()
    },

    // 切换自动刷新
    toggleAutoRefresh() {
      this.autoRefresh = !this.autoRefresh
      if (this.autoRefresh) {
        this.startAutoRefresh()
      } else {
        this.stopAutoRefresh()
      }
    },

    // 开始自动刷新
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.loadData()
      }, 5000) // 5秒刷新一次
    },

    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },

    // 初始化WebSocket
    initWebSocket() {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.host}${process.env.VUE_APP_BASE_API}/ws/monitor`

      try {
        this.ws = new WebSocket(wsUrl)
        this.ws.onopen = () => {
          console.log('WebSocket连接成功')
        }
        this.ws.onmessage = (event) => {
          const data = event.data
          if (data.startsWith('STATS:')) {
            const stats = JSON.parse(data.substring(6))
            this.stats = { ...this.stats, ...stats }
          }
        }
        this.ws.onclose = () => {
          console.log('WebSocket连接关闭')
        }
        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error)
        }
      } catch (error) {
        console.error('WebSocket连接失败:', error)
      }
    },

    // 显示消息详情
    showMessageDetail(message) {
      this.currentMessage = message
      this.messageDetailVisible = true
    },

    // 时间格式化
    parseTime(time, pattern) {
      if (!time) return ''
      return this.$parseTime(time, pattern)
    }
  }
}
</script>

<style scoped>
.statistic-card {
  text-align: center;
  margin-bottom: 20px;
}
.statistic-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
}
.statistic-label {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}
.rate {
  color: #67C23A;
  font-size: 12px;
}
.message-count {
  margin: 0 2px;
  padding: 2px 6px;
  background: #f4f4f5;
  border-radius: 3px;
  font-size: 12px;
}
.box-card {
  margin-bottom: 20px;
}
</style>
